import DEFAULT from "./defaults";
import { NODE_TYPE_ELE, LEFT_KEY, RIGHT_KEY, ANIMATION_NAME } from "./constant";

class baseSlider {
  constructor(el, options) {
    if (el.nodeType !== NODE_TYPE_ELE) {
      throw new Error("需要传入DOM元素");
    }
    this.options = {
      ...DEFAULT,
      ...options,
    };

    //选取元素
    const sliderEl = el;
    const sliderContentEl = sliderEl.querySelector(".slider-content");
    const sliderItems = sliderContentEl.querySelectorAll(".slider-item");

    this.sliderEl = sliderEl;
    this.sliderContentEl = sliderContentEl;
    this.sliderItems = sliderItems;

    //初始化指标
    this.minIndex = 0;
    this.maxIndex = this.sliderItems.length - 1;
    this.curIndex = this.getCorrectIndex(this.options.initialIndex);

    //获取移动距离
    this.moveDis = this.sliderItems[0].offsetWidth;

    this.init();
  }

  getCorrectIndex(index) {
    if (index > this.maxIndex) return this.minIndex;
    if (index < this.minIndex) return this.maxIndex;
    return index;
  }

  init() {
    // 设置宽度
    this.setItemWidth();
    this.setContentWidth();

    //设置初始位置, 不带动画跳转
    this.move(this.getDistance(this.options.initialIndex));

    //开启动画
    if (this.options.animation) {
      this.openAnimation();
    }
    //开启自动切换
    if (this.options.autoPlay) {
      this.autoPlay();
    }
  }

  //自动切换
  autoPlay() {
    const { autoplay } = this.options;
    this.pause;
    if (autoplay) {
      this.autoPlayTimer = setInterval(() => {
        this.next();
      }, autoplay);
    }
  }

  //暂停自动切换
  pause() {
    clearInterval(this.autoPlayTimer);
  }

  //开启动画
  openAnimation() {
    this.sliderContentEl.classList.add(ANIMATION_NAME);
  }

  //移动方法
  prev() {
    this.to(this.curIndex - 1);
  }
  next() {
    this.to(this.curIndex + 1);
  }

  //to方法
  to(index) {
    index = this.getCorrectIndex(index);
    if (this.curIndex === index) return;
    this.curIndex = index;
    let dis = this.getDistance();
    if (this.options.animation) {
      this.moveWithAnimation(dis);
    } else {
      this.move(dis);
    }
  }

  //动画调整速度
  setAnimationSpeed(speed = this.options.speed) {
    this.sliderContentEl.style.transitionDuration = `${speed}ms`;
  }

  // 关闭动画
  closeAnimation() {
    this.setAnimationSpeed(0);
  }

  //不带动画移动
  move(dis) {
    this.sliderContentEl.style.transform = `translateX(${dis}px)`;
  }

  //带动画移动
  moveWithAnimation(dis) {
    this.openAnimation();
    this.setAnimationSpeed();
    this.move(dis);
    this.sliderContentEl.addEventListener(
      "transitionend",
      () => {
        this.closeAnimation;
      },
      false
    );
  }

  getDistance(index = this.curIndex) {
    return -this.moveDis * index;
  }

  //计算距离

  setItemWidth() {
    for (let item of this.sliderItems) {
      item.style.width = `${this.moveDis}px`;
    }
  }
  setContentWidth() {
    this.sliderContentEl.style.width = `${
      this.moveDis * this.sliderItems.length
    }px`;
  }
  //开启动画
}

export default baseSlider;
